package com.bossien.flink.common;

import com.bossien.common.common.SpringContextHolder;
import com.bossien.flink.annatation.JHandler;
import com.bossien.flink.interfaces.IExamHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Map;

/***
 * @author 胡春林
 * 程序正式启动入口
 */
@Slf4j
@Component
@Order(value = 1)
public class InitializationHandlerCommand implements CommandLineRunner{

    @Override
    public void run(String... args) throws Exception {

        Map<String,IExamHandler> examHandlerMap = SpringContextHolder.getApplicationContext().getBeansOfType(IExamHandler.class);

        if(null == examHandlerMap || examHandlerMap.size() == 0) {
            log.info("没有需要运行的作业---{}" + this.getClass().getName());
            return;
        }
        for(Map.Entry<String, IExamHandler> entry : examHandlerMap.entrySet())
        {
            JHandler jHandler = AnnotationUtils.findAnnotation(entry.getValue().getClass(),JHandler.class);
            if(jHandler != null)
            {
                Method[] methods = entry.getValue().getClass().getDeclaredMethods();
                if(methods != null)
                {
                    for (Method method : methods)
                    {
                        if(method.getReturnType() instanceof Object && method.getReturnType().getName().indexOf("Object") > 0)
                            continue;
                        if (method.getName().equals("handler")) {

                            log.info("业务调用作业名称:{}",jHandler.value());
                            boolean result =(Boolean) method.invoke(entry.getValue(), null);
                            String resultMsg = result == true ? "成功":"失败";

                            log.info("{}执行"+resultMsg,entry.getKey());

                        }
                    }
                }
            }

        }


    }
}
